package com.itbooking.core.interceptor;

import com.itbooking.core.annotation.LoginToken;
import com.itbooking.core.jwt.JwtOpendIdUtil;
import com.itbooking.core.threalLocal.UserThreadLocal;
import com.itbooking.pojo.UserDo;
import com.itbooking.service.IUserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 *
 */
@Log4j2
public class AuthIntercetor implements HandlerInterceptor {

    @Autowired
    private JwtOpendIdUtil jwtOpendIdUtil;
    @Autowired
    private IUserService userService;

    @Value(("${spring.profiles.active}"))
    private String profiles;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 http 请求头中取出 token
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 安全问题的产生 --test/dev?t=222 但是生成环境是不能够在t 就算你加了也必须使用token
        if(!StringUtils.isEmpty(profiles) && !profiles.equalsIgnoreCase("prod")) {
            String test = request.getParameter("t");
            if (!StringUtils.isEmpty(test)) {
                return true;
            }
        }

        // 判断有没有这个注解如果有。直接放行通过
        if (method.isAnnotationPresent(LoginToken.class)) {
            LoginToken loginToken = method.getAnnotation(LoginToken.class);
            if (loginToken.required()) {
                return true;
            }
        }

        // 这里需要校验
        // token怎么创建(token接口)
        // 微信小程会在调用每个接口的时候 把token的放在请求头或者参数中。从而拦截器进行拦截获取
        // 1：获取token
        // 2: 解析token
        response.setCharacterEncoding("UTF-8");
        // 3：比较token 如果一致，直接返回true 否则返回false
        String token = request.getHeader("Authrization");
        log.info("拦截器获取到接口方法是：{}，的token是:{}",method.getName(),token);
        if(StringUtils.isEmpty(token)){
            response.getWriter().print("服务器出错，没有token");
            return false;
        }

        String openid = jwtOpendIdUtil.parseJWT(token).get("openid",String.class);
        if(StringUtils.isEmpty(openid)){
            return false;
        }


        //根据openid去数据库查询一次，看是否存在该用户，存在就进行比较，如果一致就通过，如果不一致就不通过.
        UserDo userDo = userService.getUserByOpenid(openid);
        if(userDo==null){
            // 你可以注册你用户 + return true;
            response.getWriter().print("服务器出错，没有token");
            return false;
        }

        UserThreadLocal.put(userDo);

        log.info("你执行接口是：{}",method.getName());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
